package com.gz.furnitures.filter;

import com.gz.furnitures.utils.JdbcUtilsByDruid;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class TransactionFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            //放行
            //假如某一个用到的实现类的sql语句写错了，那么会被捕捉到错误，进入catch
            filterChain.doFilter(servletRequest, servletResponse);
            //统一提交
            JdbcUtilsByDruid.commit();
        } catch (Exception e) {
            //这里是从BasicServlet(BasicServlet从其子类捕获到的异常，一层套一层传到这)捕获到的异常!!!
            JdbcUtilsByDruid.rollback(); //回滚
            //这里要抛出异常给tomcat，tomcat根据errorpage 来显示对应页面(如500.jsp)
            //可以体会:异常机制可以参与业务逻辑
            throw new RuntimeException(e);
//            e.printStackTrace();
        }
    }

    @Override
    public void destroy() {

    }
}
